<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="6">
        <div class="app-container">
          <el-input
            v-model="filterText"
            placeholder="关键字"
            style="margin-bottom:30px;"
          />
          <el-tree
            ref="tree2"
            :data="data2"
            :props="defaultProps"
            :filter-node-method="filterNode"
            class="filter-tree"
            default-expand-all
            @node-click="clickNode"
          />
        </div>
      </el-col>

      <el-col :span="18">
        <div class="app-container">
          <el-row :gutter="20">
            <el-table
              v-loading="listLoading"
              :data="list"
              element-loading-text="Loading"
              border
              fit
              highlight-current-row
              @row-click="rowClick"
            >
              <el-table-column
                align="center"
                label="序号"
                width="95"
                v-if="false"
              >
                <template slot-scope="scope">
                  {{ scope.row.id }}
                </template>
              </el-table-column>
              <el-table-column label="设备类型编号">
                <template slot-scope="scope">
                  {{ scope.row.deviceTypeNo }}
                </template>
              </el-table-column>
              <el-table-column label="设备类型名称">
                <template slot-scope="scope">
                  {{ scope.row.deviceTypeName }}
                </template>
              </el-table-column>
              <el-table-column label="设备号" width="110" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.row.deviceNo }}</span>
                </template>
              </el-table-column>
              <el-table-column label="设备名称" width="110" align="center">
                <template slot-scope="scope">
                  {{ scope.row.deviceName }}
                </template>
              </el-table-column>
              <el-table-column
                class-name="status-col"
                label="备注"
                width="110"
                align="center"
              >
                <template slot-scope="scope">
                  <el-tag :type="scope.row.comment">{{
                    scope.row.comment
                  }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="created_at"
                label="Display_time"
                width="200"
              >
                <template slot-scope="scope">
                  <i class="el-icon-time" />
                  <span>{{ scope.row.display_time }}</span>
                </template>
              </el-table-column>
            </el-table>
            <pagination
              v-show="total > 0"
              :total="total"
              :page.sync="listQuery.page"
              :limit.sync="listQuery.limit"
              :page-sizes="listQuery.pageSizes"
              @pagination="fetchData"
            />
          </el-row>
          <el-row :gutter="20" class="relationContainer">
            <el-col :span="3" class="el-custom-title">设备参数:</el-col>
            <el-col :span="21">
              <el-button-group style="float:right;">
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  class="el-button--mini"
                  @click="handleCreate"
                  >添加</el-button
                >
              </el-button-group></el-col
            >
          </el-row>
          <el-row :gutter="20">
            <el-table
              v-loading="listLoading"
              :data="list2"
              element-loading-text="Loading"
              border
              fit
              highlight-current-row
            >
              <el-table-column
                align="center"
                label="序号"
                width="95"
                v-if="false"
              >
                <template slot-scope="scope">
                  {{ scope.row.id }}
                </template>
              </el-table-column>
              <el-table-column label="参数名称" width="110" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.row.deviceParaName }}</span>
                </template>
              </el-table-column>

              <el-table-column label="起始值">
                <template slot-scope="scope">
                  {{ scope.row.paraStartValue }}
                </template>
              </el-table-column>
              <el-table-column label="结束值">
                <template slot-scope="scope">
                  {{ scope.row.paraEndValue }}
                </template>
              </el-table-column>
              <el-table-column label="产能值" width="110" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.row.productivitySpeed }}</span>
                </template>
              </el-table-column>

              <el-table-column
                class-name="status-col"
                label="产能数量"
                width="110"
                align="center"
              >
                <template slot-scope="scope">
                  <span>{{ scope.row.productivityQuantity }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                align="center"
                width="230"
                class-name="small-padding fixed-width"
              >
                <template slot-scope="{ row, $index }">
                  <el-button
                    type="primary"
                    size="mini"
                    @click="handleUpdate(row)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    v-if="row.status != 'deleted'"
                    size="mini"
                    type="danger"
                    @click="deleteDeviceParameter(row, $index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <pagination
              v-show="total2 > 0"
              :total="total2"
              :page.sync="listQuery2.page"
              :limit.sync="listQuery2.limit"
              :page-sizes="listQuery2.pageSizes"
              @pagination="getDeviceParams"
            />
          </el-row>
        </div>
      </el-col>
    </el-row>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="120px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="设备参数编号" prop="deviceParaNo">
          <el-input v-model="temp.deviceParaNo" />
        </el-form-item>
        <el-form-item label="设备参数名称" prop="deviceParaName">
          <el-input v-model="temp.deviceParaName" />
        </el-form-item>
        <el-form-item label="设备" prop="deviceId">
          <el-select
            v-model="temp.deviceId"
            class="filter-item"
            placeholder="请选择"
          >
            <el-option
              v-for="item in lstAllDevices"
              :key="item.id"
              :label="item.deviceName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="起始值" prop="startValue">
          <el-input v-model="temp.paraStartValue" />
        </el-form-item>
        <el-form-item label="结束值">
          <el-input v-model="temp.paraEndValue" />
        </el-form-item>
        <el-form-item label="速率">
          <el-input v-model="temp.productivitySpeed" />
        </el-form-item>
        <el-form-item label="产能值">
          <el-input
            v-model="temp.productivityQuantity"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
            placeholder="Please input"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="
            dialogStatus === 'create'
              ? createDeviceParameter()
              : updateDeviceParameter()
          "
        >
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDeviceTypeList } from "@/api/device/mesDeviceType";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import request from "@/utils/request";
import {
  createDeviceParam,
  updateDeviceParam,
  deleteDeviceParam
} from "@/api/device/mesDeviceParameter";
import { getList } from "@/api/device/mesDevice";

export default {
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger"
      };
      return statusMap[status];
    }
  },
  data() {
    const validateDeviceId = (rule, value, callback) => {
      let val = parseInt(value);
      if (val == null || val < 1) {
        callback(new Error("请选择设备!"));
      } else {
        callback();
      }
    };
    return {
      filterText: "",
      data2: [],
      defaultProps: {
        children: "children",
        label: "deviceTypeName"
      },
      list: null,
      list2: null,
      listLoading: true,
      total: 0,
      total2: 0,
      listQuery: {
        page: 1,
        limit: 6,
        pageSizes: [6, 10, 14]
      },
      //deviceParameter
      listQuery2: {
        page: 1,
        limit: 6,
        pageSizes: [6, 10, 14]
      },
      currentDeviceId: 0,
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "创建"
      },
      lstAllDevices: [],
      rules: {
        deviceParaNo: [
          {
            required: true,
            message: "设备参数编号不能为空！",
            trigger: "change"
          }
        ],
        paraStartValue: [
          { type: "float", message: "起始值必须为浮点数x.x", trigger: "change" }
        ],
        paraEndValue: [
          { type: "float", message: "结束值必须为浮点数x.x", trigger: "change" }
        ],
        productivitySpeed: [
          { type: "float", message: "速率必须为浮点数x.x", trigger: "change" }
        ],
        productivityQuantity: [
          { type: "integer", message: "产能必须为浮点数x.x", trigger: "change" }
        ],
        deviceParaName: [
          { required: true, message: "设备参数名称不能为空！", trigger: "blur" }
        ],
        deviceId: [
          {
            required: true,
            message: "请选择设备！",
            trigger: "change",
            validator: validateDeviceId
          }
        ]
      },
      temp: {
        id: undefined,
        deviceParaNo: "",
        deviceTypeName: "",
        deviceId: 0,
        deviceName: "请选择",
        paraStartValue: 0.0,
        paraValue: 0.0,
        productivitySpeed: 0.0,
        productivityQuantity: 0
      }
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree2.filter(val);
    }
  },
  created() {
    this.fetchData();
    this.getTreeData();
    this.getDeviceParams(0);
    this.getAllDevices();
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data.deviceTypeName.indexOf(value) !== -1;
    },
    fetchData() {
      this.listLoading = true;
      let params = {
        name: "",
        page: this.listQuery.page,
        size: this.listQuery.limit
      };
      getList(params).then(response => {
        this.list = response.data.records;
        this.total = response.data.total;
        this.listLoading = false;
      });
    },
    getTreeData() {
      this.listLoading = true;
      let that = this;
      getDeviceTypeList().then(response => {
        //增加一个根节点
        let root = [
          {
            id: 0,
            deviceTypeName: "全部",
            children: response.data
          }
        ];
        that.data2 = root;
        that.listLoading = false;
      });
    },
    clickNode(data, node, obj) {
      let params = {
        name: data.deviceTypeNo,
        page: this.listQuery2.page,
        size: this.listQuery2.limit
      };
      getList(params).then(response => {
        this.list = response.data.records;
        this.total = response.data.total;
        this.listLoading = false;
      });
    },
    getDeviceParams() {
      let params = {
        deviceId: this.currentDeviceId,
        page: this.listQuery2.page,
        size: this.listQuery2.limit
      };

      return request({
        url: "/mes-device-parameter/GetDeviceParameters",
        method: "get",
        params
      }).then(response => {
        this.list2 = response.data.records;
        this.total2 = response.data.total;
        this.listLoading = false;
      });
    },
    rowClick(row, column, event) {
      this.currentDeviceId = row.id;
      this.getDeviceParams();
    },
    createDeviceParameter() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.temp.id = 0; //自增
          createDeviceParam(this.temp).then(() => {
            this.list2.unshift(this.temp);
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "添加成功！",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    updateDeviceParameter() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          updateDeviceParam(this.temp).then(() => {
            const index = this.list2.findIndex(v => v.id === this.temp.id);
            this.list2.splice(index, 1, this.temp);
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "修改成功！",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    deleteDeviceParameter(row, index) {
      deleteDeviceParam(row.id).then(() => {
        const index = this.list2.findIndex(v => v.id === row.id);
        this.list2.splice(index, 1);
        this.dialogFormVisible = false;
        this.$notify({
          title: "Success",
          message: "删除成功！",
          type: "success",
          duration: 2000
        });
      });
    },
    getAllDevices() {
      request({
        url: "/mes-device/AllDevices",
        method: "get"
      }).then(response => {
        this.lstAllDevices = response.data;
        this.lstAllDevices.splice(0, 0, { id: 0, deviceName: "请选择" });
      });
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        deviceParaNo: "",
        deviceTypeName: "",
        deviceId: 0,
        paraStartValue: 0.0,
        paraEndValue: 0.0,
        productivitySpeed: 0.0,
        productivityQuantity: 0
      };
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row); // copy obj
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    }
  }
};
</script>
<style>
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>
